package com.kefu.sys.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.common.context.KefuContext;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.service.KefuService;
import com.kefu.sys.mapper.SysMenuMapper;
import com.kefu.sys.model.SysMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class SysMenuService extends AbstractKefuService<SysMenu>{

	@Autowired
	protected SysMenuMapper sysMenuMapper;

	public int getMaxWeight(String parentId) {
		return sysMenuMapper.getMaxWeight(parentId);
	}

	public List<?> listTenantTree() {
		String roleId = KefuContext.getKefuContext().getTenantId();//默认角色id跟企业id一样
		List<SysMenu> dataList = sysMenuMapper.getMenuByRoleId(roleId);//查询企业默认角色权限
		List<TreeNode<String>> nodeList = CollUtil.newArrayList();
		for(SysMenu item : dataList){
			nodeList.add((new TreeNode<>(item.getId(),item.getParentId(),item.getName(),item.getWeight())));
		}
		return TreeUtil.build(nodeList, "0");
	}

	public List<?> listAllTree() {
		List<SysMenu> dataList = sysMenuMapper.selectList(Wrappers.lambdaQuery(SysMenu.class));
		List<TreeNode<String>> nodeList = CollUtil.newArrayList();
		for(SysMenu item : dataList){
			TreeNode<String> node = new TreeNode<>(item.getId(),item.getParentId(),item.getName(),item.getWeight());
			node.setExtra(BeanUtil.beanToMap(item));
			nodeList.add(node);
		}
		return TreeUtil.build(nodeList, "0");
	}

	public List<SysMenu> getMenuByRoleId(String roleId) {
		return sysMenuMapper.getMenuByRoleId(roleId);
	}
}
